import { WS_ADDRESS } from '../configs';

function useWebSocket(handleMessage) {
  const ws = new WebSocket(WS_ADDRESS);

  const init = () => {
    bindEvent();
  }

  function bindEvent() {
    ws.addEventListener('open', handleOpen, false);
    ws.addEventListener('close', handleClose, false);
    ws.addEventListener('error', handleError, false);
    // 作为处理后端发送回来的数据可用形参函数来处理，对应不同页面或模块，进行扩展
    ws.addEventListener('message', handleMessage, false);
  }

  function handleOpen(e) {
    console.log('FE: WebSocket open', e)
  }

  function handleClose(e) {
    console.log('FE: WebSocket close', e)
  }

  function handleError(e) {
    console.log('FE: WebSocket error', e)
  }

  // function handleMessage(e) {
  //   console.log('FE: WebSocket messgae', e)
  // }

  init();

  return ws;
}

export default useWebSocket;